<?php
    function input_csv($handle)  
    {  
        $out = array ();  
        $n = 0;  
        while ($data = fgetcsv($handle, 10000))  
        {  
            $num = count($data);  
            for ($i = 0; $i < $num; $i++)  
            {  
                $out[$n][$i] = $data[$i];  
            }  
            $n++;  
        }  
        return $out;  
    }  
    if ($_FILES["file"]["error"] > 0)
    {
        echo "错误：" . $_FILES["file"]["error"] . "<br>";
    }
    else
    {

        echo "上传文件名: " . $_FILES["file"]["name"] . "<br>";
        echo "文件类型: " . $_FILES["file"]["type"] . "<br>";
        echo "文件大小: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "文件临时存储的位置: " . $_FILES["file"]["tmp_name"];
        $filename = $_FILES['file']['tmp_name'];  
        if(empty ($filename))  
        {  
            echo '请选择要导入的CSV文件！';  
            exit;  
        }  
        $handle = fopen($filename, 'r');  
        $result = input_csv($handle); //解析csv  
        $len_result = count($result);  
        if($len_result==0)  
        {  
            echo '没有任何数据！';  
            exit;  
        }  
        $data_values = "";
        for($i = 0; $i < $len_result; $i++) //循环获取各字段值  
        {  
            $id = iconv('GBK', 'utf-8', $result[$i][0]); //中文转码  
            $name = iconv('GBK', 'utf-8', $result[$i][1]);  
            $class = iconv('GBK', 'utf-8', $result[$i][2]);  
            $data_values .= "('$id','$name','$class'),";  
        }  
        $data_values = substr($data_values,0,-1); //去掉最后一个逗号  
        fclose($handle); //关闭指针  


        	//数据库连接
        $dbhost = 'localhost';  // mysql服务器主机地址
        $dbuser = 'root';            // mysql用户名
        $dbpass = '';          // mysql用户名密码
        $conn = mysqli_connect($dbhost, $dbuser, $dbpass);
        if(! $conn )
        {
            die('Could not connect: ' . mysqli_error());
        }
        $tmp = "数据库连接成功!";
        echo $tmp;
        mysqli_select_db( $conn, 'tmp' );  //选择数据库
        $query = mysqli_query($conn,"insert into student (id,name,class) values $data_values"); //批量插入数据表中  
        if($query)  
        {  
            echo '导入成功！';  
        }else{  
            echo '导入失败！';  
        }   

    }






?>